package com.health.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.health.common.common.ErrorCode;
import com.health.common.exception.BusinessException;
import com.health.common.model.vo.UserKeyVO;
import com.health.common.service.util.SDKUtils;
import com.health.user.mapper.DoctorMapper;
import com.health.user.model.dto.doctor.DoctorRegisterRequest;
import com.health.user.model.entity.Doctor;
import com.health.user.service.DoctorService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.fisco.bcos.sdk.v3.codec.ContractCodecException;
import org.fisco.bcos.sdk.v3.model.TransactionReceipt;
import org.fisco.bcos.sdk.v3.transaction.manager.AssembleTransactionProcessor;
import org.fisco.bcos.sdk.v3.transaction.model.exception.TransactionBaseException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static com.health.common.constant.ContractConstants.ADD_DOCTOR;
import static com.health.common.constant.ContractConstants.ADD_HOSPITAL;

/**
* @author zhexueqi
* @description 针对表【doctor(医生表)】的数据库操作Service实现
* @createDate 2024-08-25 01:31:13
*/
@Service
@Slf4j
public class DoctorServiceImpl extends ServiceImpl<DoctorMapper, Doctor>
    implements DoctorService {

    @Resource
    private SDKUtils sdkUtils;
//
//    @Value("${system.contract.contractName}")
//    private String CONTRACT_NAME;
//
//    @Value("${system.contract.address}")
//    private String CONTRACT_ADDRESS;

    @Value("${system.hospital.contract.contractName}")
    private String CONTRACT_NAME;

    @Value("${system.hospital.contract.address}")
    private String CONTRACT_ADDRESS;

    @Value("${system.hospital.contract.abi}")
    private String ABI;
    @Value("${system.hospital.contract.bin}")
    private String BIN;

    /**
     * 创建mysql医生用户
     */
    @Override
    @Transactional
    public void createDoctorToMysql(DoctorRegisterRequest doctorRegisterRequest,UserKeyVO userKeyVO) {
        if (getOne(new QueryWrapper<Doctor>().eq("doctor_account", doctorRegisterRequest.getDoctorAccount())) != null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"医院账号已存在");
        }
        Doctor doctor = new Doctor();
        doctor.setDoctorAccount(doctorRegisterRequest.getDoctorAccount());
        doctor.setDoctorName(doctorRegisterRequest.getDoctorName());
        doctor.setDepartment(doctorRegisterRequest.getDepartment());
        doctor.setStartTime(doctorRegisterRequest.getStartTime());
        doctor.setHospitalAddress(doctorRegisterRequest.getHospitalAddress());
        doctor.setGender(doctorRegisterRequest.getGender());
        doctor.setDoctorAddress(userKeyVO.getAddress());
        if (!save(doctor)){
            throw new BusinessException(ErrorCode.SQL_ERROR,"注册医生失败");
        }
        log.info("创建mysql医生用户成功");
    }


    /**
     * 创建区块链医生用户
     * @param userKeyVO
     * @param userAccount
     */
    @Override
    public void createDoctor(UserKeyVO userKeyVO, String userAccount) throws TransactionBaseException, ContractCodecException {
        QueryWrapper<Doctor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("doctor_account",userAccount);
        Doctor doctor = this.getOne(queryWrapper);

        if (doctor == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在");
        }

        List<Object> funcParams = new ArrayList<>();
        funcParams.add(userKeyVO.getAddress());
        funcParams.add(doctor.getDoctorName());
        funcParams.add(doctor.getHospitalAddress());
        funcParams.add(doctor.getDepartment());
        funcParams.add(doctor.getStartTime().toString());

        AssembleTransactionProcessor assembleTransactionProcessor = sdkUtils.transactionProcessor(CONTRACT_NAME,userKeyVO.getPrivateKey(),ABI,BIN);
        TransactionReceipt transactionReceipt = assembleTransactionProcessor.sendTransactionAndGetReceiptByContractLoader(CONTRACT_NAME, CONTRACT_ADDRESS, ADD_DOCTOR, funcParams);

        if (!transactionReceipt.isStatusOK()){
            log.error("报错信息:{}",transactionReceipt.getMessage());
            throw new BusinessException(ErrorCode.CONTRACT_ERROR,"区块链注册失败");
        }
        log.info("区块链注册成功，交易哈希为：{}",transactionReceipt.getTransactionHash());
    }

}




